package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Editora;

public class EditoraDaoImpl implements EditoraDao {
	Connection c;

	public EditoraDaoImpl() {
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}

	@Override
	public void salvaEditora(Editora editora) throws SQLException {
		String sql = "INSERT INTO editoras VALUES (?,?,?,?,?,?,?,?)";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, editora.getIdEditora());
		ps.setString(2, editora.getNomeEditora());
		ps.setInt(3, editora.getCNPJ());
		ps.setString(4, editora.getEndereco());
		ps.setInt(5, editora.getNum());
		ps.setString(6, editora.getBairro());
		ps.setString(7, editora.getEmail());
		ps.setInt(8, editora.getTelefone());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaEditora(Editora editora) throws SQLException {
		String sql = "UPDATE editoras SET nomeEditora = ?, " + "CNPJ = ?, "
				+ "endereco = ?, " + "num = ?, " + "bairro = ?, "
				+ "email = ?, " + "telefone = ? WHERE idEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);

		ps.setString(1, editora.getNomeEditora());
		ps.setInt(2, editora.getCNPJ());
		ps.setString(3, editora.getEndereco());
		ps.setInt(4, editora.getNum());
		ps.setString(5, editora.getBairro());
		ps.setString(6, editora.getEmail());
		ps.setInt(7, editora.getTelefone());
		ps.setInt(8, editora.getIdEditora());

		ps.execute();
		ps.close();

	}

	@Override
	public void excluiEditora(Editora editora) throws SQLException {
		String sql = "DELETE editoras WHERE idEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, editora.getIdEditora());
		ps.execute();
		ps.close();

	}

	@Override
	public Editora pesquisaEditora(Editora editora) throws SQLException {
		Editora ed = new Editora();
		String sql = "SELECT nomeEditora, CNPJ, endereco, num, bairro, "
				+ "email, telefone FROM editoras " + "WHERE idEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, editora.getIdEditora());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {

			ed.setIdEditora(rs.getInt("idEditora"));
			ed.setNomeEditora(rs.getString("nomeEditora"));
			ed.setCNPJ(rs.getInt("CNPJ"));
			ed.setEndereco(rs.getString("endereco"));
			ed.setNum(rs.getInt("num"));
			ed.setBairro(rs.getString("bairro"));
			ed.setEmail(rs.getString("email"));
			ed.setTelefone(rs.getInt("telefone"));

		}
		ps.close();
		rs.close();
		return ed;
	}

}
